package com.helloandroid.models

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.business.Analyse
import com.business.AnalyseKey
import com.helloandroid.AppUtil
import com.helloandroid.ext.ParseResult
import com.helloandroid.tools.Http.asyncHttpReq
import com.helloandroid.tools.MyLog
import com.helloandroid.tools.MyTimeUtils
import com.helloandroid.vo.*
import dai.android.util.AndroidUtils
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.lang.Exception

data class RelatedMatch(val matchId:Int,var state: UserMatchState)
data class MatchData(val matchLst:ArrayList<TTMatchInfo>,val relatedLst:ArrayList<RelatedMatch>)

class TTHBSData(
        val m3:MatchData,
        val m8:MatchData,
        val m3Ratio:Float,
        val m8Ratio:Float,
        var joinCount:Int, // 累计参加次数
)

class HBMatchViewModel: ViewModel(){

    fun parse(jsonStr:String):ParseResult{
        try {
            val jsonObj = JSONObject(jsonStr)
            val err = jsonObj.getInt("err")
            if (err == 0){
                val localTodayTitle = MyTimeUtils.timeToInt(AppUtil.sysTime)
                val cates = jsonObj.getJSONObject("cate")
                val m3Ratio = cates.getInt("m3000") / 10000f
                val m8Ratio = cates.getInt("m8000") / 10000f

                // 提取比赛信息
                val matchs = jsonObj.getJSONArray("matchs")
                val m3Lst = ArrayList<TTMatchInfo>()
                val m8Lst = ArrayList<TTMatchInfo>()
                for (i in 0 until matchs.length()){
                    val match = matchs.getJSONObject(i)

                    val matchId = match.getInt("match_id")
                    val title = match.getInt("title")
                    val type = match.getInt("cate")
                    val people = match.getInt("people")
                    val peopleOK = match.getInt("peopleOK")
                    val robots = match.getInt("robots")
                    val robotsOKRate = match.getInt("robotsOKRate")

                    // 计算比赛状态
                    val matchState = when{
                        localTodayTitle == title -> MatchState.Running
                        localTodayTitle > title -> MatchState.Ended
                        else -> MatchState.Unstarted
                    }

                    val tmpLst:ArrayList<TTMatchInfo>
                    val totalMoney:Float
                    if (type == 3000){
                        tmpLst = m3Lst
                        totalMoney = (m3Ratio * (people + robots) * 100).toInt() / 100f
                    }else{
                        tmpLst = m8Lst
                        totalMoney = (m8Ratio * (people + robots) * 100).toInt() / 100f
                    }

                    val info = TTMatchInfo(
                            matchId = matchId,
                            title = title,
                            type = type,
                            people = people,
                            peopleOK = peopleOK,
                            robots = robots,
                            robotsOKRate = robotsOKRate,
                            matchState = matchState,
                            totalMoney = totalMoney
                    )
                    tmpLst.add(info)
                }

                // 玩家数据信息
                val userMatch = jsonObj.getJSONArray("userMatch")
//                val todayTitle = jsonObj.getInt("todayTitle")

                // 整理信息
                val m3RelatedLst = ArrayList<RelatedMatch>()
                val m8RelatedLst = ArrayList<RelatedMatch>()
                for (i in 0 until userMatch.length()){
                    val item = userMatch.getJSONObject(i)
                    val matchId = item.getInt("match_id")
                    val matchStatus = item.getInt("match_status")

                    // 判断当前的比赛状态
                    val userMatchState = UserMatchState.parseValue(matchStatus)
                    val relatedMatch = RelatedMatch(matchId,userMatchState)
                    if (m3Lst.find { it.matchId == matchId } != null){
                        m3RelatedLst.add(relatedMatch)
                    }else{
                        m8RelatedLst.add(relatedMatch)
                    }
                }

                // 组合到一起
                val m3Data = MatchData(m3Lst,m3RelatedLst)
                val m8Data = MatchData(m8Lst,m8RelatedLst)
                val joinCount = jsonObj.getInt("joinCount")
                val hbsData = TTHBSData(m3Data,m8Data,m3Ratio,m8Ratio,joinCount)
                return ParseResult(err,hbsData)
            }else{
                return ParseResult(err,jsonObj.getString("msg"))
            }
        }catch (e: Exception){
            return ParseResult(1000, "解析错误")
        }
    }

    fun getInfo(callback:(Boolean,TTHBSData?)->Unit){
        viewModelScope.launch {
            val jsonStr = asyncHttpReq("match/info?user_id=${AppUtil.user.user_id}")

            // 天天红包赛信息.  消息格式和以前的不一致
            val parseResult = parse(jsonStr)
            if (parseResult.err != 0){
                // 发现错误
                MyLog.info("err:${parseResult.err},msg:${parseResult.obj as String}")
                callback(false,null)
            }else{
                val hbsData = parseResult.obj as TTHBSData
                callback(true,hbsData)
            }
        }
    }

    fun award(matchId: Int,callback:(Boolean,Int)->Unit){

        if (!AndroidUtils.networkConnected(AppUtil.app)){
            AppUtil.toast("请打开网络!")
            callback(false,0)
            return
        }

        viewModelScope.launch {
            val jsonStr = asyncHttpReq("match/award?user_id=${AppUtil.user.user_id}&match_id=${matchId}")
            val jsonObj = JSONObject(jsonStr)
            val err = jsonObj.getInt("err")
            if (err == 0){
                val data = jsonObj.getJSONObject("data")
                val money = data.getInt("money")
                val addMoney = data.getInt("addMoney")
                AppUtil.setMoney(money)
                callback(true,addMoney)
            }else{
                MyLog.info("err:${err},msg:${jsonObj.getString("msg")}")
                callback(false,0)
            }
        }


//        viewModelScope.launch {
//            val defer = async(Dispatchers.IO){
//                httpAward()
//            }
//            val jsonStr = defer.await()
//            MyLog.elog("服务端返回:$jsonStr")
//            val gson = GUtils.getGson()
//            val jsonObj = (gson.fromJson(jsonStr) as JsonElement).asJsonObject
//            val err = jsonObj.get("err").asInt
//            if(err == 0){
//                val moneyAward = gson.fromJson<MoneyAward>(jsonObj.get("data").asString)
//                AppUtil.toast("恭喜,领取${String.format("%.2f",moneyAward.count/100.0f)}块成功!")
//                AppUtil.increaseMoney(moneyAward.count)
//                val wrapData = wrapDataProxy.value!!
//
//                // 领取了,相应的状态设置成已更新
//                val matchData = wrapData.getMatchData(type)
//                matchData.relatedLst.find {
//                    it.matchId == matchId
//                }?.let {
//                    it.state = UserMatchState.Geted
//                }
//                wrapDataProxy.value = wrapData
//            }else{
//                MyLog.elog("err:$err,msg:${jsonObj.get("msg").asString}")
//            }
//        }
    }

    // 参与天天红包赛
    fun tthbsTakePart(matchId:Int,callback:(Boolean,Int,Int,Int)->Unit){
        if (!AndroidUtils.networkConnected(AppUtil.app)){
            AppUtil.toast("请连接到网络!")
            callback(false,-1,0,0)
            return
        }
        Analyse.report(AnalyseKey.TTHBS_TakePart)
        viewModelScope.launch {
            val jsonStr = asyncHttpReq("match/join?user_id=${AppUtil.user.user_id}&match_id=${matchId}")
            val jsonObj = JSONObject(jsonStr)
            val err = jsonObj.getInt("err")
            if (err == 0){
                val data = jsonObj.getJSONObject("data")
                val people = data.getInt("people")
                val robots = data.getInt("robots")
                val robotsOKRate = data.getInt("robotsOKRate")
                callback(true,people,robots,robotsOKRate)

                // 上报
                AppUtil.appViewModel().zhuanReportTask(Type.TianTianHongBao)
            }else{
                MyLog.info("err:${err},msg:${jsonObj.getString("msg")}")
                callback(false,-1,0,0)
            }
        }
    }
}

